import fetch from 'cross-fetch';

const options = {
  eth: {
    method: 'GET',
    headers: {
      Accept: 'application/json',
      'X-API-KEY': ' efbd09f6acbd4cefa5f2bb8b424063f2',
    },
  },
  rinkeby: {},
};

const api_url = {
  eth: 'https://api.opensea.io/api/v1',
  rinkeby: 'https://testnets-api.opensea.io/api/v1',
  goerli: 'https://testnets-api.opensea.io/api/v1',
};

export const sleep = (ms) => {
  return new Promise((resolve) => setTimeout(resolve, ms));
};

export const getFloorPrice = async (address, chain) => {
  return new Promise(async (resolve) => {
    try {
      const fetch_contract_url = `${api_url[chain]}/asset_contract/${address}`;
      console.log('fetch_contract_url', fetch_contract_url);
      const contractRes = await fetch(fetch_contract_url, options[chain]);
      const contractResJson = await contractRes.json();
      await sleep(chain == 'eth' ? 500 : 1100);
      const url = `${api_url[chain]}/collection/${contractResJson['collection']['slug']}/stats`;
      console.log('url', url);
      const res = await fetch(url, options[chain]);
      const resJson = await res.json();
      await sleep(chain == 'eth' ? 500 : 1100);
      resolve(
        resJson['stats']['floor_price'] ? resJson['stats']['floor_price'] : 0,
      );
    } catch (e) {
      console.log('res-error', e);
      resolve(0);
    }
  });
};
